package com.fangs.yehwangglobal.base;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.fangs.yehwangglobal.utils.URLBase64;
import com.google.gson.Gson;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class AccountService implements AccountServiceIntf {

    private static final String COLUMN_LOGININFO = "logininfo";
    private final SharedPreferences prefs,sharedPreferences;
    private JSONObject loginJsonObj;
    private String json = "";

    AccountService(Context context) {
        prefs = context.getSharedPreferences("yehwang_user_account", Context.MODE_PRIVATE);
        //获取一个文件名为test、权限为private的xml文件的SharedPreferences对象
        sharedPreferences = context.getSharedPreferences("test", Context.MODE_PRIVATE);
        LoginInfo();
    }

    private JSONObject LoginInfo() {
        if (loginJsonObj == null) {
            loadLoginInfo();
        }
        if (loginJsonObj == null) {
            loginJsonObj = new JSONObject();
        }
        return loginJsonObj;
    }

    private void loadLoginInfo() {
        try {
            String base64 = this.prefs.getString(COLUMN_LOGININFO, null);
            if (base64 != null) {
                byte[] bytes = URLBase64.decode(base64);
                json = new String(bytes, StandardCharsets.UTF_8);
                loginJsonObj = new JSONObject(json);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void saveLoginInfo() {
        try {
            String accountInfo = LoginInfo().toString();
            prefs.edit().putString(COLUMN_LOGININFO, URLBase64.encode(accountInfo.getBytes(StandardCharsets.UTF_8))).apply();

            Gson gson = new Gson();
            SessionModel baseInfo = gson.fromJson(accountInfo, SessionModel.class);
            //得到SharedPreferences.Editor对象，并保存数据到该对象中
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("email", baseInfo.email);
            //保存key-value对到文件中
            editor.commit();

        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.i("log", LoginInfo().toString());
    }

    private <T> T getLoginInfoValue(String key, T defaultValue) {
        if (defaultValue == null) {
            throw new RuntimeException("defaultValue can't be null ");
        }
        Object result = null;
        if (LoginInfo().has(key)) {
            try {
                result = LoginInfo().get(key);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        try {
            return result == null ? defaultValue : (T) result;
        } catch (Exception e) {
            return defaultValue;
        }
    }

    @Override
    public String email() {
        return getLoginInfoValue("email", "");
    }

    @Override
    public String password() {
        return getLoginInfoValue("password", "");
    }

    @Override
    public String token() {
        return getLoginInfoValue("token", "");
    }

    @Override
    public int language() {
        return getLoginInfoValue("language", 0);
    }

    @Override
    public String currency() {
        return getLoginInfoValue("currency", "EUR");
    }

    @Override
    public void updateAccount(SessionModel sessionModel) {
        if (sessionModel == null) return;

        Moshi moshi = new Moshi.Builder().build();
        JsonAdapter<SessionModel> jsonAdapter = moshi.adapter(SessionModel.class);
        SessionModel oldSessionModel = null;
        try {
            oldSessionModel = jsonAdapter.fromJson(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (oldSessionModel == null) {
            oldSessionModel = new SessionModel();
        }
        if (sessionModel.email != null) {
            oldSessionModel.email = sessionModel.email;
        }
        if (sessionModel.password != null) {
            oldSessionModel.password = sessionModel.password;
        }
        if (sessionModel.token != null) {
            oldSessionModel.token = sessionModel.token;
        }
        if (sessionModel.language > 0 && sessionModel.language < 6) {
            oldSessionModel.language = sessionModel.language;
        }
        if (sessionModel.currency != null) {
            oldSessionModel.currency = sessionModel.currency;
        }
        json = jsonAdapter.toJson(oldSessionModel);
        try {
            loginJsonObj = new JSONObject(json);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        saveLoginInfo();
    }

}
